package com.zrx.app.android.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.AppCompatSpinner;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zrx.app.android.R;
import com.zrx.app.android.UTIL.ImageUTIL;
import com.zrx.app.android.UTIL.RemoteConn;
import com.zrx.app.android.UTIL.ZRXUTIL;
import com.zrx.app.android.fragment.ImageFrag;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/*征信查询*/
public class CreditActivity extends BaseActivity {
    private EditText creditTypeET;
    private AppCompatSpinner spinner;
    private List<String> data;
    private String creditTypeValue;
    private static final String TAG = "CreditActivity";
    public static void startActivity(Context context) {
        Intent intent = new Intent(context,CreditActivity.class);
        context.startActivity(intent);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_credit);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        creditTypeET= (EditText) findViewById(R.id.credit_type_et);
        spinner=(AppCompatSpinner)findViewById(R.id.credit_type_spinner);
        data=getData();
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,data);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                creditTypeValue=data.get(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        Button btnQuery = (Button) findViewById(R.id.btn_query);
        Button btnList = (Button) findViewById(R.id.btn_listQuery);
        final ImageFrag mIdCard1= (ImageFrag) getFragmentManager().findFragmentById(R.id.idCard1);
        final ImageFrag mIdCard2=(ImageFrag) getFragmentManager().findFragmentById(R.id.idCard2);
        final ImageFrag mAuthSignature=(ImageFrag) getFragmentManager().findFragmentById(R.id.authSignature);
        final ImageFrag mAuthPhoto=(ImageFrag) getFragmentManager().findFragmentById(R.id.authPhoto);
        final ImageFrag mAuth3rdPartPhoto=(ImageFrag) getFragmentManager().findFragmentById(R.id.auth3rdPartPhoto);
        final EditText textName=(EditText)findViewById(R.id.text_name);
        final EditText textIdCardNum=(EditText)findViewById(R.id.text_idCardNum);
        final EditText textPhoNum=(EditText)findViewById(R.id.text_PhoNum);
        final EditText textCreditCardNum=(EditText)findViewById(R.id.text_CreditCardNum);
      /*  findViewById(R.id.text_idCardNum);*/
        final CreditActivity _self = this;


       try {
           btnQuery.setOnClickListener(new View.OnClickListener(){
               @Override
               public void onClick(View v) {//提交查询按钮
                   try {
                       String creditType=creditTypeET.getText().toString().trim();
                       Log.e("征信类型",creditType.toString());
                       if("".equals(creditTypeValue)||null==creditTypeValue){
                           Toast.makeText(CreditActivity.this,"请选择征信类型",Toast.LENGTH_LONG).show();
                           return;
                       }
//                if(!"担保人".equals(creditTypeValue)||creditTypeValue!="主贷人"){
//                    Toast.makeText(CreditActivity.this,"征信类型必须是担保人或主贷人",Toast.LENGTH_LONG).show();
//                    return;
//                }
                       JSONObject re = RemoteConn.getInstance().queryCredit(textName.getText().toString(), textIdCardNum.getText().toString(), textPhoNum.getText().toString(), textCreditCardNum.getText().toString(),
                               creditTypeValue,mIdCard1.getPhotoPath(), mIdCard2.getPhotoPath(), mAuthSignature.getPhotoPath(), mAuthPhoto.getPhotoPath(), mAuth3rdPartPhoto.getPhotoPath());
                       if (re != null && re.getIntValue("code") == 0) {
                           new File(mIdCard1.getPhotoPath()).delete();
                           new File(mIdCard2.getPhotoPath()).delete();
                           new File(mAuthSignature.getPhotoPath()).delete();
                           new File(mAuthPhoto.getPhotoPath()).delete();
                           new File(mAuth3rdPartPhoto.getPhotoPath()).delete();

                           AlertDialog.Builder ad = new AlertDialog.Builder(v.getContext());
                           ad.setTitle("提交成功");
                           ad.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                               @Override
                               public void onClick(DialogInterface dialog, int which) {
                                   dialog.dismiss();
                               }
                           });
                           ad.show();
                       } else {
                           AlertDialog.Builder ad = new AlertDialog.Builder(v.getContext());
                           ad.setTitle("提交失败");
                           ad.setMessage(re == null ? "当前网络状态不好" : re.toJSONString());
                           ad.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                               @Override
                               public void onClick(DialogInterface dialog, int which) {
                                   dialog.dismiss();
                               }
                           });
                           ad.show();
                       }
                       Log.d(TAG, re.toJSONString());
                   }catch (Exception e){
                   Log.e(TAG,e.getMessage());
                   }
               }
           });
       }catch (Exception e){                                //异常捕获然后重启活动，重新提交
           Log.e(TAG,e.getMessage());
       }


       try {
           btnList.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {//查看记录按钮
                   {
                       try {
                           JSONObject re = RemoteConn.getInstance().listCredit();
                         /*  Log.e("re数据",String.valueOf(re));*/
                           LayoutInflater inflater = LayoutInflater.from(_self);
                           View dialog = inflater.inflate(R.layout.dialog_credit_list, null);
                           GridLayout content = (GridLayout) dialog.findViewById(R.id.dialog_credit_list_content);

                           AlertDialog.Builder ad = new AlertDialog.Builder(v.getContext());
                           if (re != null && re.getIntValue("code") == 0) {
                               JSONObject data = re.getJSONObject("data");
                               JSONArray arr = data.getJSONArray("content");
                               for (int i = 0; i < arr.size(); ++i) {
                                   JSONObject ele = arr.getJSONObject(i);

                                   final ImageView imageView = new ImageView(_self);
                                   imageView.setLayoutParams(new LinearLayout.LayoutParams(1000, 150));
                                   imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                                   String state = ele.getString("state");
                                   TextView textView = new TextView(_self);
                                   String text = "";
                                   String mobile = "";
                                   String bankCard = "";
                                   String _name = "";
                                   String _idCardNum = "";
                                   String creditType = "";
                                   if (ele.getString("name") != null) {
                                       _name = ele.getString("name");
                                   } else _name = "";
                                   if (ele.getString("idCardNum") != null) {
                                       _idCardNum = ele.getString("idCardNum");
                                   } else _idCardNum = "";
                                   if (ele.getString("mobile") != null) {
                                       mobile = ele.getString("mobile");
                                   } else mobile = "";
                                   if (ele.getString("bankCard") != null) {
                                       bankCard = ele.getString("bankCard");
                                   } else bankCard = "";
                                   if (ele.getString("creditType") != null) {
                                       creditType = ele.getString("creditType");
                                   } else creditType = "";

                                   text += "姓    名:" + _name.toString() + "\n";
                                   text += "身份证号:" + _idCardNum.toString() + "\n";
                                   text += "状    态:" + state + "\n";
                                   text += "手机号:" + mobile.toString() + "\n";
                                   text += "银行卡号" + bankCard.toString() + "\n";
                                   text += "征信担保类型" + creditType.toString() + "\n";
                                   textView.setText(text);
                                   content.addView(textView);
                                   content.addView(imageView);
                                   if ("CREDIT_DONE".equals(state)) {         //LOAN_DONE
                                       String fileId = ele.getString("creditPic");
                                       File dir = new File(ZRXUTIL.path + "/cache/");
                                       if (!dir.exists())
                                           dir.mkdirs();
                                       String filePath = ZRXUTIL.path + "/cache/" + fileId;
                                       File file = new File(filePath);
                                       if (file.exists()) {
                                           imageView.setImageURI(Uri.fromFile(file));
                                       } else {
                                           imageView.setImageResource(R.drawable.loading);
                                           final String _fileId = fileId;
                                           final String _filePath = filePath;
                                           AsyncTask at = new AsyncTask() {
                                               @Override
                                               protected Object doInBackground(Object[] params) {
                                                   return RemoteConn.getInstance().getFile(_fileId, _filePath);//_fileId这个是获取到的id,_filePath保存的路径
                                               }

                                               @Override
                                               protected void onPostExecute(Object o) {
                                                   super.onPostExecute(o);
                                                   if (Boolean.TRUE.equals(o)) {
                                                       imageView.setImageBitmap(ImageUTIL.fitToImageView(imageView, _filePath));
                                                   } else {
                                                       imageView.setImageResource(R.drawable.fail);
                                                   }
                                               }
                                           };
                                           at.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Object());
                                       }
                                   } else
                                       imageView.setImageResource(R.drawable.pending);
                               }
                           }
                           ad.setView(dialog);

                           ad.setNegativeButton("确认", new DialogInterface.OnClickListener() {
                               @Override
                               public void onClick(DialogInterface dialog, int which) {
                                   dialog.dismiss();
                               }
                           });
                           ad.show();

                           Log.d(TAG, re.toJSONString());
                       }catch (Exception e){
                           Log.e(TAG,e.getMessage());
                       }
                   }
               }
           });
       }catch (Exception e){
           Log.e(TAG,e.getMessage());
       }
    }

    private List<String> getData() {
        List<String>data=new ArrayList<>();
        data.add("担保人");
        data.add("主贷人");
        return data;
    }

    @Override
    protected String getModuleName() {
        return "征信模块";
    }
}
